<template>
  <div style="padding:10px;background-color:#f8f8f8;overflow:hidden;">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <div style="overflow:hidden;border:1px solid #ccc;position:relative;">
<el-select v-model="selectedPoleName" filterable remote reserve-keyword :placeholder="$t('map.searchPlaceholder')" :remote-method="remoteMethod" :loading="loading" @change="locatePole" @wheel.stop v-show="true">
<el-option v-for="item in deviceList" :key="item.id" :label="item.lightName" :value="item.id"/></el-select>
          <div ref="map" style="height:874px;min-height:500px;"/>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import {getDeviceStatistic,listDeviceShort} from '@/api/iot/device'
import {listNotice,getNotice} from "@/api/system/notice";
import CountTo from 'vue-count-to'
import * as echarts from 'echarts';
require('echarts/theme/macarons') // echarts theme
import {loadBMap} from '@/utils/map.js'
//ECharts的百度地图扩展，可以在百度地图上展现点图，线图，热力图等可视化
require('echarts/extension/bmap/bmap')
import {getLightpole,listDeviceUsers,listLightpole} from '@/api/iot/lightpole'
import item from '@/layout/components/Sidebar/Item.vue'
import {listUser} from '@/api/iot/tool'
export default {
  name:"Index",
  components:{CountTo},
  data() {
    return {
      poleNames: [],
      selectedPoleName: null,
      map: null, // 添加map对象
      selectedPole: null, // 存储选中的灯杆信息
      mapLoaded: false, // 添加标记变量
      tooltipTimer: null, // 用于存储定时器ID
      debounceTimeout: null,
      firstPoleLat: null,  // 用于存储第一个设备的纬度
      firstPoleLng: null,  // 用于存储第一个设备的经度
      loading: true,
      open: false,
      noticeList: [],
      notice: {},
      isAdmin: false,
      deviceList: [],
      deviceStatistic: {},
      deviceCount: 0,
      countData: {devicesOn:0,devicesOff:0,},
      version: "3.8.0",
      tableData: []
    };
  },
  created() {
    this.init();
    this.getAllDevice();
    this.getDeviceStatistic();
    //this.fetchAllLightpoles(); // 组件创建时获取所有灯杆名称
  },
  mounted() {
    this.loading = true;
    //this.fetchAllLightpoles();
    this.setMap();
  },
  methods: {
    splitt(center){
      var myChart = echarts.init(this.$refs.map);
      if (myChart) {myChart.dispose();}
      myChart = echarts.init(this.$refs.map);
      // 在组件方法内部定义翻译函数，确保可以访问this
      const getTranslatedText = (key) => {
        return this.$t(key);
      };
      function convertTimestamp(timestamp) {
        if (!timestamp) return '';
        const date = new Date(timestamp * 1000);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        const seconds = date.getSeconds().toString().padStart(2, '0');
        return `${year}${getTranslatedText('map.year')}${month}${getTranslatedText('map.month')}${day}${getTranslatedText('map.day')} ${hours}:${minutes}:${seconds}`;
      }
      let convertData = function(data, status) {
        var res = [];
        data = data || [];
        for (var i = 0; i < data.length; i++) {
          var geoCoord = [data[i].lng, data[i].lat];
          if (geoCoord && data[i].status && data[i].status.toLowerCase() === status.toLowerCase() && data[i].lightName) {
            res.push({
              name: data[i].lightName,
              value: geoCoord,
              lightonline: data[i].lightonline,
              //city: data[i].faProject.city,
              createtime: data[i].createtime ,
              address: data[i].address == null ? '' : data[i].address, // 预留地址字段
            });
          }
        }
        return res;
      };
      let seriesData = convertData(this.deviceList, 'normal');
      if (seriesData.length === 0) {
        seriesData = convertData(this.deviceList[1], 'normal');
      }
      const getAddressByCoord = (lng, lat, callback) => {
        const geocoder = new BMap.Geocoder();
        const point = new BMap.Point(lng, lat);
        geocoder.getLocation(point, (rs) => {
          //console.log('Geocoder result:', rs); // 打印出完整的rs对象
          if (rs && rs.address) {
            const addressComponent=rs.addressComponents;
            const address=`${addressComponent.province}${addressComponent.city}${addressComponent.district}${addressComponent.street}${addressComponent.streetNumber}`;
            //console.log('解析地址:',address);
            callback(null, address);
          } else {
            console.error('BMap Geocoder error:', rs);
            callback(this.$t('map.addressParseFailed') + (rs ? rs.status : 'undefined'), null); // 发生错误时返回错误消息
          }
        });
      };
      var option = {
        title: {
          text: this.$t('map.deviceDistribution') + this.countData.devicesOn + '）',
          target: "_blank",
          textStyle:{color:'#333',textBorderColor:'#e3ff00',textBorderWidth:10,fontWeight:'bold'},
          top: 10,
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
            let address = params.data.address; // 默认使用传入的地址
            try {
              // 获取地址（异步操作）
              getAddressByCoord(params.data.value[0], params.data.value[1], (err, result) => {
                if (err) {
                  console.error('获取地址失败:', err);
                } else {
                  address = result; // 在回调内更新 address
                   params.data.address=address ;
                }
              });
            } catch (error) {
              console.error('获取地址失败:', error);
            }
            var htmlStr = '<div style="padding:5px;line-height:28px;">';
            htmlStr += getTranslatedText('map.lightPoleName') + "： <span style='color:#409EFF'>" + params.data.name + "</span><br />";
            htmlStr += getTranslatedText('map.lightPoleStatus') + "： ";
            if (params.data.lightonline === 1) {
              htmlStr += "<span style='color:#38a800'>" + getTranslatedText('map.online') + "</span>" + "<br />";
            } else if (params.data.lightonline === 0) {
              htmlStr += "<span style='color:#F56C6C'>" + getTranslatedText('map.offline') + "</span>" + "<br />";
            }
            htmlStr += getTranslatedText('map.activationTime') + "： " + params.data.createtime + "<br />";
            htmlStr += getTranslatedText('map.location') + "： " +  params.data.address  + "<br />";
            htmlStr += '</div>';
            return htmlStr;
          }
        },
        bmap: {
          center: center,
          zoom: 17,
          roam: true,
          data: seriesData,
        },
        series: [{
          type: 'scatter',
          coordinateSystem: 'bmap',
          data: convertData(this.deviceList, 'normal').length === 0 ? convertData(this.deviceList[1], 'normal') : convertData(this.deviceList, 'normal'), // 使用转换后的数据
          symbolSize: [28, 28],
          symbol: 'image://',
          label: {
            show: true,
            position: 'bottom',
            formatter: function(params) {
              // 使用数据项的名称作为标签内容
              return params.data.name;
            },
            // 使用数据项的名称作为标签内容
            color: '#093077', // 标签文字颜色
            fontSize: 14, // 标签文字大小
            distance: 6 // 标签距离图标的距离
          },
        },
          {
            type: 'scatter', // 散点图
            coordinateSystem: 'bmap',
            data: convertData(this.deviceList, 'hidden').length === 0 ? convertData(this.deviceList[1], 'hidden') : convertData(this.deviceList, 'hidden'), // 使用转换后的数据
            symbolSize: [28, 28], // 设置图标大小
            symbol: 'image://',
            label: {
              show: true,
              position: 'bottom',
              formatter: function(params) {
                // 使用数据项的名称作为标签内容
                return params.data.name;
              },
              color: '#093077', // 标签文字颜色
              fontSize: 14, // 标签文字大小
              distance: 6 // 标签距离图标的距离
            },
          },
        ]
      };
      myChart.setOption(option);
    },
    /** 搜索方法，加入防抖功能 */
    remoteMethod(query) {
      if (this.debounceTimeout) {clearTimeout(this.debounceTimeout);}
      if (query === '') {this.deviceList = [];return;}
      this.debounceTimeout = setTimeout(() => {
        this.loading = true;
        listLightpole({ search: query }).then((response) => {
            this.deviceList = response.rows;
            if (this.deviceList.length === 0) {
              console.warn('搜索结果为空'); // 提示空数据
            }
            this.loading = false;
          }).catch((error) => {
            console.error('搜索灯杆失败:', error);
            this.loading = false;
          });
      }, 500); // 500ms 防抖延时
    },
    locatePole(id) {
      if (!id) return; // 确保ID存在
      let number = parseInt(id);
      this.loading = true;
      getLightpole(number).then(response => {
        const pole = response.data;
        if (pole && pole.lat && pole.lng) {
          this.selectedPole = pole;
          this.setMap(pole, this.selectedPole.lat, this.selectedPole.lng, 16);
        } else {
          console.error('灯杆经纬度信息不完整:', this.selectedPole);
        }
        this.loading = false;
      }).catch(error => {
        console.error('获取灯杆信息失败:', error);
        this.loading = false;
      });
    },
    /**查询所有设备 */
    getAllDevice() {
      listDeviceUsers().then(response => {
        this.deviceList = response.rows;
        this.deviceCount = response.total;
        this.countData.devicesOn = response.rows[0].devicesOn; // 添加默认值
        this.countData.devicesOff = response.rows[0].devicesOff; // 添加默认值
        this.loadMap();
      }).catch(error => {
        console.error('获取设备列表失败:', error);
      });
    },
    /**加载地图*/
    loadMap() {
      this.$nextTick(() => {
        loadBMap().then(() => {
          this.map = new BMap.Map(this.$refs.map);
          this.mapLoaded = true; // 地图已加载标记
          setTimeout(() => {
            this.getmap();
          }, 100);
        }).catch(error => {
          console.error('加载百度地图失败:', error);
        });
      });
    },
    init() {
      if (this.$store.state.user.roles.indexOf("tenant") === -1 && this.$store.state.user.roles.indexOf("general") === -1) {
        this.isAdmin = true
      }
    },
    /** 查询设备统计信息 */
    getDeviceStatistic() {
      getDeviceStatistic().then(response => {
        this.deviceStatistic = response.data;
        //console.log(deviceStatistic)
      });
    },
    // 取消按钮
    closeDetail() {
      this.title = "";
      this.open = false;
    },
    setMap(pole,lat,log,zoom) {
      // 在组件方法内部定义翻译函数，确保可以访问this
      const getTranslatedText = (key) => {
        return this.$t(key);
      };
      if (!this.map) {
        console.error('地图未初始化');
        return;
      }
      var myChart = echarts.init(this.$refs.map);
      function convertTimestamp(timestamp) {
        if (!timestamp) return '';
        const date = new Date(timestamp * 1000);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        const seconds = date.getSeconds().toString().padStart(2, '0');
        return `${year}${this.$t('map.year')}${month}${this.$t('map.month')}${day}${this.$t('map.day')} ${hours}:${minutes}:${seconds}`;
      }
      if(myChart){
        myChart.dispose()
      }
      myChart = echarts.init(this.$refs.map);
      let convertData = function (pole) {
        var res = [];
        var geoCoord = [pole.lng, pole.lat];
        res.push({
          name: pole.lightName,
          value: geoCoord,
          status: pole.status,
          lightonline: pole.lightonline,
          createtime: pole.createtime,
          address: pole.address == null ? '' : pole.address, // 预留地址字段
        })
        return res;
      };
      // 使用地理编码API获取地址
      const getAddressByCoord = (lng, lat, callback) => {
        const geocoder = new BMap.Geocoder();
        const point = new BMap.Point(lng, lat);
        geocoder.getLocation(point, (rs) => {
         // console.log('Geocoder result:', rs); // 打印出完整的rs对象
          if (rs && rs.address) {
            // 使用rs.addressComponents来构建地址字符串
            const addressComponent = rs.addressComponents;
            const address = `${addressComponent.province}${addressComponent.city}${addressComponent.district}${addressComponent.street}${addressComponent.streetNumber}`;
           // console.log('解析地址:', address);
            callback(null, address);
          } else {
            //console.error('BMap Geocoder error:', rs);
            callback(this.$t('map.addressParseFailed') + (rs ? rs.status : 'undefined'), null); // 发生错误时返回错误消息
          }
        });
      };
      let seriesData = convertData(pole);
      var option = {
        title: {
          text: this.$t('map.deviceDistribution') + this.countData.devicesOn + '）',
          target: "_blank",
          textStyle: {
            color: '#333',
            textBorderColor: '#e3ff00',
            textBorderWidth: 10,fontWeight: 'bold'
          },
          top: 10,
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: function (params) {
            let address = params.data.address; // 默认使用传入的地址
            try {
              // 获取地址（异步操作）
              getAddressByCoord(params.data.value[0], params.data.value[1], (err, result) => {
                if (err) {
                  console.error('获取地址失败:', err);
                } else {
                  address = result; // 在回调内更新 address
                  params.data.address=address ;
                }
              });
            } catch (error) {
              console.error('获取地址失败:', error);
            }
            var htmlStr = '<div style="padding:5px;line-height:28px;">';
            htmlStr += getTranslatedText('map.lightPoleName') + "： <span style='color:#409EFF'>" + params.data.name + "</span><br />";
            htmlStr += getTranslatedText('map.lightPoleStatus') + "： ";
            if (params.data.lightonline === 1) {
              htmlStr += "<span style='color:#38a800'>" + getTranslatedText('map.online') + "</span>" + "<br />";
            } else if (params.data.lightonline === 0) {
              htmlStr += "<span style='color:#F56C6C'>" + getTranslatedText('map.offline') + "</span>" + "<br />";
            }
            htmlStr += getTranslatedText('map.activationTime') + "： " + params.data.createtime + "<br />";
            htmlStr += getTranslatedText('map.location') + "： " +  params.data.address  + "<br />";
            htmlStr += '</div>';
            return htmlStr;
          }
        },
        bmap: {
          center: [log, lat],
          zoom: zoom,
          roam: true,
          data: seriesData,
        },
        series: [{
          type: 'scatter',
          coordinateSystem: 'bmap',
          data: seriesData, // 使用转换后的数据
          symbolSize: [30, 30],
          symbol: 'image://',
          label: {
            show: true,
            position: 'bottom',
            formatter: function (params) {
              // 使用数据项的名称作为标签内容
              return params.data.name;
            },
            // 使用数据项的名称作为标签内容
            color: '#093077', // 标签文字颜色
            fontSize: 14, // 标签文字大小
            distance: 6 // 标签距离图标的距离
          },
        },
          {
            type: 'scatter', // 散点图
            coordinateSystem: 'bmap',
            data: convertData(this.deviceList, 'hidden').length ===0 ?convertData(this.deviceList[1], 'hidden'):convertData(this.deviceList, 'hidden'), // 使用转换后的数据
            symbolSize: [30, 30], // 设置图标大小
            symbol: 'image://',
            label: {
              show: true,
              position: 'bottom',
              formatter: function(params) {
                // 使用数据项的名称作为标签内容
                return params.data.name;
              },
              // 使用数据项的名称作为标签内容
              color: '#093077', // 标签文字颜色
              fontSize: 14, // 标签文字大小
              //border: '1px solid #5663b5', // 添加边框，1px 宽度，实线，颜色与文本颜色相同
              // borderRadius: '4px', // 边框圆角，可根据需要调整
              // padding: '4px', // 添加内边距，使边框与文本之间有一定的空间
              distance: 6 // 标签距离图标的距离
            },
          },
        ]
      };
      myChart.setOption(option);
    },
    /** 地图 */
    getmap() {
      if (!this.map) {
        console.error('地图未初始化');
        return;
      }
      var user = this.$store.state.user;
      this.isAdmin = user && user.roles && user.roles.includes('admin');
      console.log("是否为管理员####", this.isAdmin);
      // 根据用户角色决定地图的初始位置
      listLightpole().then(response => {
        this.deviceList = response.rows;
        console.log("获取设备数据", response);
        this.loading = false;
        let center = [119.981718, 31.81565]; // 默认位置
        if (!this.isAdmin && this.deviceList.length > 0) {
          //console.log("99999")
          const firstDevice = this.deviceList[0];
          if (firstDevice.lat && firstDevice.lng) {
            center = [parseFloat(firstDevice.lng), parseFloat(firstDevice.lat)];
            //console.log("第一个设备的经纬度:", center);
          } else {
            console.error('第一个设备的经纬度信息不完整');
          }
        } else {
          center = [119.981718, 31.81565]; // 默认位置
        }
        if (this.map) {
        } else {
          console.error('地图未初始化');
        }
        this.splitt(center);
      })
    }
  },
};
</script>

<style lang="scss" scoped>
html, body, #app {
  height: 100%;
  margin: 0;
}
.phone {
  height: 729px;
  width: 370px;
  background-image: url("../assets/images/phone.png");
  background-size: cover;
  margin: 0 auto;
}
.phone-container {
  height: 618px;
  width: 343px;
  position: relative;
  top: 46px;
  left: 12px;
  background-color: #fff;
}
.content {
  line-height: 24px;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 10px;
}
.panel-group {
  .card-panel-col {
    margin-bottom: 10px;
  }
  .card-panel {
    height: 68px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    color: #666;
    border: 1px solid #eee;
    border-radius: 5px;
    background-color: #fff;
    transition: all 0.2s ease;
    &:hover {
      .card-panel-icon-wrapper {
        color: #fff;
      }
      .icon-blue {
        background: #36a3f7;
      }
      .icon-green {
        background: #34bfa3;
      }
      .icon-red {
        background: #F56C6C;
      }
      .icon-orange {
        background: #E6A23C;
      }
    }
    .icon-blue {
      color: #36a3f7;
    }
    .icon-green {
      color: #34bfa3;
    }
    .icon-red {
      color: #F56C6C;
    }
    .icon-orange {
      color: #E6A23C;
    }
    .card-panel-icon-wrapper {
      float: left;
      margin: 10px;
      padding: 10px;
      transition: all 0.38s ease-out;
      border-radius: 6px;
    }
    .card-panel-icon {
      float: left;
      font-size: 30px;
    }
    .card-panel-description {
      float: right;
      font-weight: bold;
      margin: 15px;
      margin-left: 0px;
      .card-panel-text {
        line-height: 14px;
        color: rgba(0, 0, 0, 0.45);
        font-size: 14px;
        margin-bottom: 12px;
        text-align: right;
      }
      .card-panel-num {
        font-size: 18px;
      }
    }
  }
}
</style>
